package com.jewelry.crm.controller;

import com.jewelry.crm.model.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;


import java.util.Collection;

import static com.jewelry.crm.common.Common.logger;
import static com.jewelry.crm.model.bo.UserBo.*;

@Controller
@RequestMapping("/users")
public class UserController {

    @RequestMapping(value="/list", method = RequestMethod.GET)
    public ModelAndView list() throws Throwable{
        Collection users = getAllUsers();
        logger.info("Going to show the list");
        return new ModelAndView("users/userList", "users", users);
    }

    @RequestMapping(value="/show/{id}", method = RequestMethod.GET)
    public ModelAndView show(@PathVariable(value="id") int id) throws Throwable{
        User user = getUserById(id);
        return new ModelAndView("users/userShow", "user", user);
    }

    @RequestMapping(value="/delete/{id}", method = RequestMethod.GET)
    public ModelAndView delete(@PathVariable(value="id") int id) throws Throwable{
        deleteUser(getUserById(id));
        return new ModelAndView( "redirect:/users/list.html" );
    }

    @RequestMapping(value="/edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable(value="id") int id) throws Throwable{
        User user = getUserById(id);
        return new ModelAndView("users/userEdit", "user", user);
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    public ModelAndView updateUsers (@PathVariable(value="id") int id, @ModelAttribute("user") User user) throws Throwable {

        User oldUser = getUserById(id);

        oldUser.setFirstname(user.getFirstname());
        oldUser.setLastname(user.getLastname());
        oldUser.setEmail(user.getEmail());
        updateUser(oldUser);
        return new ModelAndView ( "redirect:/users/show/" + id +".html" );
    }

    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public ModelAndView addUsers( @ModelAttribute("user") User user) {
        return new ModelAndView ("users/userAdd");
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ModelAndView saveUser ( @ModelAttribute("user") User user) throws Throwable {
        addUser(user);
        return new ModelAndView ( "redirect:/users/list.html" );
    }


}
